<template>
    <div class="table-of-router">
      <div style="position: relative">
        <i @click="recovery" class="iconfont icon-return" id="backHome-icon"></i>
        <el-input
          id="search-input"
          class="search"
          type="textarea"
          :rows="1"
          resize="none"
          :maxlength="70"
          @keydown.enter.native="toSearch"
          placeholder="【搜索格式】name={}url={}role={}disable={} ,回车触发搜索"
          v-model="searchContent">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <div class="opt-btn">
          <a href="javascript:;"  @click="addInfo">
            <i class="el-icon-circle-plus-outline" title="新增接口"></i>
          </a>
          <a href="javascript:;" @click="handleSynchr">
            <i class="el-icon-refresh" title="同步接口"></i>
          </a>
          <a href="javascript:;" @click="handleReset">
            <i class="el-icon-refresh-right" title="重置接口"></i>
          </a>
        </div>
      </div>
      <el-table
        v-if="noResponse"
        v-loading="loading"
        style="width: 100%;height: 390px;margin: 10px auto;z-index: 1">
      </el-table>
      <el-empty v-if="isEmpty" :image-size="200"></el-empty>
      <div v-if="!isEmpty && !noResponse">
        <el-table
          :header-row-style="{height:'35px'}"
          :header-cell-style="{background:'#f5f7fa',padding:'0px'}"
          :row-style="{height:'30px'}"
          :cell-style="{padding:'0px'}"
          size='small'
          border
          style="width: 100%"
          :data="tableData"
          stripe>
          <el-table-column
            :row-style="{height:'30px'}"
            class="table-of-router"
            fixed
            prop="name"
            label="接口描述"
            width="340"
            sortable>
          </el-table-column>
          <el-table-column
            class="table-of-router"
            prop="url"
            label="接口路径"
            width="320"
            sortable>
          </el-table-column>
          <el-table-column
            class="table-of-router"
            prop="role"
            label="所属角色"
            width="120"
            sortable>
          </el-table-column>
          <el-table-column
            class="table-of-router"
            prop="disableTag"
            label="是否可用"
            width="100"
            sortable>
          </el-table-column>
          <el-table-column
            class="table-of-router"
            fixed="right"
            label="操作"
            width="150">
            <template slot-scope="scope" class="table-of-router">
              <el-button @click="handleView(scope.row)" type="text" size="small" style="color: #007cda">查看</el-button>
              <el-button @click="handleEdit(scope.row)" type="text" size="small" style="color: #00a800">编辑</el-button>
              <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color: #eb0000">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="!isEmpty && !noResponse"
          background
          layout="prev, pager, next"
          :total=pageTotal
          @current-change="handleCurrentChange(currentPage)"
          :current-page.sync = currentPage
          class="page">
        </el-pagination>
      </div>
      <el-dialog :title="title"
                 :visible.sync="dialogFormVisible"
                 :show-close="false"
                 :close-on-click-modal="false"
                 width="50%">
        <el-form :model="form" ref="form" label-width="100px">
          <el-form-item label="接口描述" :label-width="formLabelWidth"
                        prop="name"

                        :rules="[
                                  { required: true, message: '接口描述不能为空'}
                                ]">
            <el-input clearable style="width: 90%;" v-model="form.name" autocomplete="off" v-if="enable"></el-input>
            <el-input clearable style="width: 90%;" v-model="form.name" autocomplete="off" v-else disabled></el-input>
          </el-form-item>
          <el-form-item label="接口路径" :label-width="formLabelWidth"
                        prop="url"
                        :rules="[
                                  { required: true, message: '接口路径不能为空'}
                                ]">
            <el-input clearable style="width: 90%;" v-model="form.url" autocomplete="off" v-if="enable"></el-input>
            <el-input clearable style="width: 90%;" v-model="form.url" autocomplete="off" v-else disabled></el-input>
          </el-form-item>
          <el-form-item label="所属角色" :label-width="formLabelWidth"
                        prop="role"
                        :rules="[
                                  { required: true, message: '所属角色不能为空'}
                                ]">
            <el-select clearable v-model="form.role" placeholder="请选择活动区域" v-if="enable">
              <el-option label="user" value="user"></el-option>
              <el-option label="admin" value="admin"></el-option>
              <el-option label="user&admin" value="user&admin"></el-option>
            </el-select>
            <el-select clearable v-model="form.role" placeholder="请选择活动区域" v-else disabled>
              <el-option label="user" value="user"></el-option>
              <el-option label="admin" value="admin"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否可用" :label-width="formLabelWidth"
                        prop="disableTag"
                        :rules="[
                                  { required: true, message: '是否可用不能为空'}
                                ]">
            <el-select clearable v-model="form.disableTag" placeholder="请选择活动区域" v-if="enable">
              <el-option label="可用" value=0></el-option>
              <el-option label="禁用" value=1></el-option>
            </el-select>
            <el-select clearable v-model="form.disableTag" placeholder="请选择活动区域" v-else disabled>
              <el-option label="可用" value=0></el-option>
              <el-option label="禁用" value=1></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close('form')">关闭</el-button>
          <el-button type="primary" @click="submitForm('form')" v-if="enable">提交</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "AdminSetting-router",
        data() {
            return{
                isSearch: false,
                searchContent:'name={}url={}role={}disable={}',
                searchContentBk:'name={}url={}role={}disable={}',
                tableData: [],
                dialogFormVisible: false,
                enable:true,
                title:"",
                form: {
                    id: '',
                    name: '',
                    url: '',
                    role: '',
                    disableTag: 0,
                    deleteTag: 0,
                },
                formLabelWidth: '100px',
                baseURL1:"http://localhost:8081/interface/add/",
                baseURL2:"http://localhost:8081/interface/synchronization",
                baseURL3:"http://localhost:8081/interface/reset",
                baseURL4:"http://localhost:8081/interface/update/",
                baseURL5:"http://localhost:8081/interface/delete/",
                baseURL6:"http://localhost:8081/interface/pages",
                baseURL7:"http://localhost:8081/interface/list/",
                baseURL8:"http://localhost:8081/interface/search/",
                loading:"true",
                isEmpty:false,
                noResponse: true,
                pageTotal:0,
                currentPage:1,  // 当前页
                option:''
            }
        },
        mounted() {
            this.$emit("component","router")
            this.getPages()
            this.getInterfaceList(this.currentPage)
        },
        methods: {
            recovery(){
                this.searchContent = this.searchContentBk
                this.isSearch = false
                this.getPages()
                this.getInterfaceList(this.currentPage)
                document.getElementById("backHome-icon").style.width = "0px"
            },
            toSearch(){
                let e = window.event || arguments[0];
                if (e.key === 'Enter' || e.code === 'Enter' || e.keyCode == 13) {
                    e.returnValue = false;  // 禁止换行
                    document.getElementById("backHome-icon").style.width = "30px"
                    this.isSearch = true
                    this.searchOpt()
                }
            },
            searchOpt(){
                // 搜索
                let r = new RegExp("^name={.*}url={.*}role={.*}disable={.*}$");   //构造正则表达式
                let res = this.searchContent.match(r);  //匹配成功返回数组，失败返回null
                if (res == null) {
                    this.$message.warning("抱歉，只允许在 { } 中填写对应搜索内容，可为空")
                    return
                } else {
                    this.isSearch = true
                    let searchContent = this.searchContent.replaceAll("/","-")
                    let searchContentArr = searchContent.split("")
                    let arr = []
                    let tempStr = ""
                    let count = 0
                    for(let i = 0; i < searchContentArr.length; i++) {
                        if (searchContentArr[i] == "{"){
                            for (let j = i+1; j < searchContentArr.length; j++){
                                if (searchContentArr[j] == "}") {
                                    i = j
                                    if (tempStr == "") {
                                        tempStr = "null"
                                    }
                                    arr[count++] = tempStr
                                    break
                                } else {
                                    tempStr += searchContentArr[j]
                                }
                            }
                        } else {
                            tempStr = ""
                        }
                    }
                    if (arr[0] == arr[1] && arr[1] == arr[2] && arr[2] == arr[3]){
                        this.$message.warning("抱歉，{ } 中的内容不支持全部相同")
                        return
                    }
                    this.noResponse=true
                    this.axios.post(this.baseURL8 + arr[0] + "/" + arr[1] + "/" + arr[2] + "/" + arr[3]).then(res=>{
                        this.noResponse=false
                        if (res.data == false){
                            this.$message.error("服务器异常")
                        } else if (res.data == "empty") {
                            this.isEmpty = true
                        } else {
                            this.isEmpty = false
                            this.pageTotal = 0
                            this.currentPage = 1
                            this.tableData = res.data
                            for (let i = 0; i< this.tableData.length; i++) {
                                if (this.tableData[i].disableTag == 0) {
                                    this.tableData[i].disableTag = "可用"
                                } else {
                                    this.tableData[i].disableTag = "禁用"
                                }
                            }
                        }
                    }).catch(
                        exception=>{
                            console.log(exception)
                        }
                    )
                }
            },
            getPages(){
                this.axios.post(this.baseURL6).then(res=>{
                    this.pageTotal = res.data * 10
                }).catch(
                    exception=>{
                        console.log(exception)
                    }
                )
            },
            getInterfaceList(currentPage){
                this.axios.post(this.baseURL7 + currentPage).then(res=>{
                    this.noResponse=false
                    if (res.data == false){
                        this.$message.error("服务器异常")
                    } else if (res.data == "empty") {
                        this.isEmpty = true
                    } else {
                        this.isEmpty = false
                        this.tableData = res.data
                        for (let i = 0; i< this.tableData.length; i++) {
                            if (this.tableData[i].disableTag == 0) {
                                this.tableData[i].disableTag = "可用"
                            } else {
                                this.tableData[i].disableTag = "禁用"
                            }
                        }
                    }
                }).catch(
                    exception=>{
                        console.log(exception)
                    }
                )
            },
            handleCurrentChange(currentPage){
                this.axios.post(this.baseURL7+currentPage).then(res=>{
                    this.noResponse=false
                    if (res.data != "empty"){
                        this.tableData = res.data
                        for (let i = 0; i< this.tableData.length; i++) {
                            if (this.tableData[i].disableTag == 0) {
                                this.tableData[i].disableTag = "可用"
                            } else {
                                this.tableData[i].disableTag = "禁用"
                            }
                        }
                    }
                    this.backTop()
                }).catch(
                    exception=>{
                        console.log(exception)
                    }
                )
            },
            addInfo(){
                this.enable = true
                this.dialogFormVisible = true
                this.title='新增接口'
                this.option = 'add'
            },
            handleSynchr(){
                this.$confirm('确定同步平台接口信息?', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    showClose: false,
                    type: 'warning'
                }).then(() => {
                    this.axios.post(this.baseURL2).then(res => {
                        if (res.data == true) {
                            this.successOpt("同步平台接口成功")
                            this.getInterfaceList(1)
                        } else {
                            this.failOpt("同步平台接口失败")
                        }
                    }).catch(
                        exception => {
                            console.log(exception)
                        }
                    )
                }).catch(() => {
                    console.log('已取消')
                });
            },
            handleReset(){
                this.$confirm('此操作将初始化所有接口配置, 是否继续?', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    showClose: false,
                    type: 'warning'
                }).then(() => {
                    this.axios.post(this.baseURL3).then(res => {
                        if (res.data == true) {
                            this.successOpt("初始化接口配置成功")
                            this.getInterfaceList(1)
                        } else {
                            this.failOpt("初始化接口配置失败")
                        }
                    }).catch(
                        exception => {
                            console.log(exception)
                        }
                    )
                }).catch(() => {
                    console.log('已取消')
                });
            },
            close(form){
                this.dialogFormVisible = false
                this.$refs[form].resetFields()
                this.form.name = ''
                this.form.url = ''
                this.form.role = ''
                this.form.disableTag = ''
            },
            submitForm(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.form.disableTag =='1'? this.form.disableTag = 1 : this.form.disableTag = 0
                        let interfaceInfo = JSON.stringify(this.form).replaceAll("/","-")
                        // return
                        if (this.option == 'add') {
                            this.axios.post(this.baseURL1 + interfaceInfo).then(res => {
                                if (res.data == true && this.isSearch) {
                                    this.close(form)
                                    this.successOpt("接口配置添加成功")
                                    this.searchOpt()
                                } else if (res.data == true && !this.isSearch) {
                                    this.close(form)
                                    this.successOpt("接口配置添加成功")
                                    this.getInterfaceList(this.currentPage)
                                } else {
                                    this.failOpt("接口配置添加失败")
                                }
                            }).catch(
                                exception => {
                                    console.log(exception)
                                }
                            )
                        } else if (this.option == 'edit') {
                            this.axios.post(this.baseURL4 + interfaceInfo).then(res => {
                                if (res.data == true && this.isSearch) {
                                    this.close(form)
                                    this.successOpt("接口配置更新成功")
                                    this.searchOpt()
                                } else if (res.data == true && !this.isSearch){
                                    this.close(form)
                                    this.successOpt("接口配置更新成功")
                                    this.getInterfaceList(this.currentPage)
                                } else {
                                    this.failOpt("接口配置更新失败")
                                }
                            }).catch(
                                exception => {
                                    console.log(exception)
                                }
                            )
                        }
                    } else {
                        return false;
                    }
                });
            },
            handleView(row) {
                this.enable = false
                this.dialogFormVisible = true
                this.title='查看接口'
                this.form.name = row.name
                this.form.url = row.url
                this.form.role = row.role
                this.form.disableTag = row.disableTag

            },
            handleEdit(row) {
                this.enable = true
                this.dialogFormVisible = true
                this.title='编辑接口'
                this.form.id = row.id
                this.form.name = row.name
                this.form.url = row.url
                this.form.role = row.role
                this.form.disableTag = row.disableTag
                this.option = 'edit'
                console.log(JSON.stringify(this.form))
            },
            handleDelete(row) {
                this.$confirm('此操作将删除此条接口配置, 是否继续?', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    showClose: false,
                    type: 'warning'
                }).then(() => {
                    row.disableTag =='禁用'? row.disableTag = 1 : row.disableTag = 0
                    let interfaceInfo = JSON.stringify(row).replaceAll("/","-")
                    this.axios.post(this.baseURL5 + interfaceInfo).then(res => {
                        if (res.data == true) {
                            this.successOpt("接口配置删除成功")
                            this.getInterfaceList(this.currentPage)
                        } else {
                            this.failOpt("接口配置删除失败")
                        }
                    }).catch(
                        exception => {
                            console.log(exception)
                        }
                    )
                }).catch(() => {
                    console.log('已取消')
                });
            },

            backTop() {
                let timer = setInterval(function () {
                    let heig = parseInt(window.scrollY);
                    if (heig > 0) {
                        window.scrollTo(0, heig-50);
                    }else {
                        clearInterval(timer);
                    }
                }, 1)
            },

            successOpt(message) {
                this.$notify({
                    title: '成功',
                    message: message,
                    type: 'success'
                })
            },
            failOpt(message) {
                this.$notify.error({
                    title: '错误',
                    message: message
                });
            }
        },
    }
</script>

<style scoped>
  .icon-return{
    display: block;
    float: left;
    width: 0px;
    height: 33px;
    line-height: 33px;
    font-size: 21px;
    color: #878787;
    transition: 0.2s;
  }
  .icon-return:hover{
    color: #1b9a92;
  }
  .search{
    width: 80%;
    height: 38px;
    transition: 0.2s;
  }
  .opt-btn{
    display: inline-block;
    width: 105px;
    height: 35px;
    line-height: 40px;
    position: absolute;
    right: 0px
  }
  .table-of-router{
    margin-top: 5px;
    overflow-x: hidden;
    overflow-y: hidden;
  }
  /*整个滚动条*/
  .table-of-router::-webkit-scrollbar {
    height: 0px;
    width: 0px;
  }
  /*滑块*/
  .table-of-router::-webkit-scrollbar-thumb {
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    background: rgba(0,0,0,0.2);
  }
  /*滑块的轨道*/
  .table-of-router::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    border-radius: 0;
    background: rgba(0,0,0,0.1);
  }
  .el-icon-circle-plus-outline,.el-icon-refresh,.el-icon-refresh-right{
    font-size: 20px;
    color: #969696;
    font-weight: bolder;
    padding: 5px 5px;
  }
  .el-icon-circle-plus-outline:hover,.el-icon-refresh:hover,.el-icon-refresh-right:hover{
    color: #ee9900;
  }
  .page{
    margin: 10px auto;
    margin-left: -10px;
  }
</style>
